import os
import re
import sqlite3

def rcg_to_db(file_name, data_dir):
    """将rcg文件中的数据输出到db文件

    Args:
        file_name: rcg文件名
        data_dir: db文件保存的路径

    Returns:
        成功返回0，失败返回err_code
        err_code:
            1.文件不是rcg文件
    """
    if file_name[-3:] != 'rcg':
        return 1  # 不是rcg文件

    # 输出数据库文件名
    pure_file_name = os.path.split(file_name)[1]
    data_name = os.path.join(data_dir, pure_file_name[:-3] + 'db')

    # 如果同名数据库文件存在，则删除已有文件
    if os.path.isfile(data_name):
        os.remove(data_name)

    print(data_name)
    # 连接数据库
    conn = sqlite3.connect(data_name)
    c = conn.cursor()

    # 创建表
    c.execute('CREATE TABLE RCDATA (CYCLE INT, \
                                    OBJECT INT, \
                                    POSX REAL, \
                                    POSY REAL, \
                                    VELX REAL, \
                                    VELY REAL, \
                                    BODYDIR REAL, \
                                    STAMINA REAL);')

    # 获取文件内容
    with open(file_name, 'r') as f_read:
        lines = f_read.readlines()

    is_special_mode = 1
    # 逐行处理
    for line in lines:
        # 如果该行是play mode行
        if line[1:9] == 'playmode':
            playmode_info = line.split(' ')
            playmode = playmode_info[2][:-2]
            if playmode == 'play_on':
                is_special_mode = 0
            else:
                is_special_mode = 1
            continue

        # 如果该行不是show行
        if line[1:5] != 'show':
            continue

        # 如果该行是show行，处理show行信息
        if is_special_mode != 0:
            continue

        dict_ball = {}  # 记录球的信息
        dict_player = {}  # 记录球员信息

        # 去掉该行中关注球员部分
        show_text = re.sub('\\(f.*?\\) ', '', line)
        show_text = show_text[:-1]  # 去除最后一个），方便后面数据处理

        # 正则表达式
        ball_ex = '\\(show (.*?) \\(\\(b\\) (.*?)\\) '
        # player_ex = '\\(\\([lr] (.*?)\\) (.*?) \\(v (.*?)\\) \\(c (.*?)\\)\\)'
        player_ex = '\\(\\([lr] (.*?)\\) (.*?) \\(v (.*?)\\) \\(s (.*?)\\) \\(c (.*?)\\)\\)'

        # 获取球数据
        match_obj = re.match(ball_ex, show_text, re.I)
        cycle = match_obj.group(1)
        dict_ball['posx'] = match_obj.group(2).split(' ')[0]
        dict_ball['posy'] = match_obj.group(2).split(' ')[1]
        dict_ball['velx'] = match_obj.group(2).split(' ')[2]
        dict_ball['vely'] = match_obj.group(2).split(' ')[3]

        # 写入球数据
        c.execute('INSERT INTO RCDATA (CYCLE,OBJECT,POSX,POSY,VELX,VELY) VALUES (' \
                  + str(cycle) + ','
                  + '0,'
                  + dict_ball['posx'] + ','
                  + dict_ball['posy'] + ','
                  + dict_ball['velx'] + ','
                  + dict_ball['vely'] + ');')

        # 获取球员数据
        it = re.finditer(player_ex, show_text)
        i = 1
        for match in it:
            '''
                match.group(1):
                match.group(2):球员位置与速度等信息
                match.group(3):球员视角等信息
                match.group(4):球员耐力等信息
                match.group(5):球员动作计数信息
            '''
            dict_player['posx'] = match.group(2).split(' ')[2]
            dict_player['posy'] = match.group(2).split(' ')[3]
            dict_player['velx'] = match.group(2).split(' ')[4]
            dict_player['vely'] = match.group(2).split(' ')[5]
            dict_player['bodydir'] = match.group(2).split(' ')[6]
            dict_player['stamina'] = match.group(4).split(' ')[0]

            # 写入球员数据
            c.execute('INSERT INTO RCDATA (CYCLE,OBJECT,POSX,POSY,VELX,VELY,BODYDIR,STAMINA) VALUES (' \
                      + cycle + ','
                      + str(i) + ','
                      + dict_player['posx'] + ','
                      + dict_player['posy'] + ','
                      + dict_player['velx'] + ','
                      + dict_player['vely'] + ','
                      + dict_player['bodydir'] + ','
                      + dict_player['stamina'] + ');')

            i += 1

    conn.commit()
    conn.close()
    return 0


def rcg_to_txt(file_name, text_dir):
    """将rcg中的数据输出到txt文件

    Args:
        file_name: rcg文件名
        text_dir: db文件保存的路径

    Returns:
        成功返回0，失败返回err_code
        err_code:
            1.文件不是rcg文件
    """
    if file_name[-3:] != 'rcg':
        return 1  # 不是rcg文件

    # 输出文本文件名
    pure_file_name = os.path.split(file_name)[1]
    text_name = os.path.join(text_dir, pure_file_name[:-3] + 'txt')

    # 如果同名文本文件存在，则删除已有文件
    if os.path.isfile(text_name):
        os.remove(text_name)

    # 打开文本文件
    f_write = open(text_name, 'w')

    # 获取文件内容
    with open(file_name, 'r') as f_read:
        lines = f_read.readlines()

    is_special_mode = 1
    print('a')
    # 逐行处理
    for line in lines:
        # 如果该行是play mode行
        if line[1:9] == 'playmode':
            playmode_info = line.split(' ')
            playmode = playmode_info[2][:-2]
            if playmode == 'play_on':
                is_special_mode = 0
            else:
                is_special_mode = 1
            continue

        # 如果该行不是show行
        if line[1:5] != 'show':
            continue

        # 如果该行是show行，处理show行信息
        if is_special_mode != 0:
            continue

        dict_ball = {}  # 记录球的信息
        dict_player = {}  # 记录球员信息

        # 去掉该行中关注球员部分
        show_text = re.sub('\\(f.*?\\) ', '', line)
        show_text = show_text[:-1]  # 去除最后一个），方便后面数据处理

        # 正则表达式
        ball_ex = '\\(show (.*?) \\(\\(b\\) (.*?)\\) '
        # player_ex = '\\(\\([lr] (.*?)\\) (.*?) \\(v (.*?)\\) \\(c (.*?)\\)\\)'
        player_ex = '\\(\\([lr] (.*?)\\) (.*?) \\(v (.*?)\\) \\(s (.*?)\\) \\(c (.*?)\\)\\)'

        # 获取球数据
        match_obj = re.match(ball_ex, show_text, re.I)
        cycle = match_obj.group(1)
        dict_ball['posx'] = match_obj.group(2).split(' ')[0]
        dict_ball['posy'] = match_obj.group(2).split(' ')[1]
        dict_ball['velx'] = match_obj.group(2).split(' ')[2]
        dict_ball['vely'] = match_obj.group(2).split(' ')[3]

        # 写入球数据
        f_write.write(cycle + '|')
        f_write.write('0|')
        f_write.write(dict_ball['posx'] + '|')
        f_write.write(dict_ball['posy'] + '|')
        f_write.write(dict_ball['velx'] + '|')
        f_write.write(dict_ball['vely'] + '\n')

        # 获取球员数据
        it = re.finditer(player_ex, show_text)
        i = 1
        for match in it:
            '''
                match.group(1):
                match.group(2):球员位置与速度等信息
                match.group(3):球员视角等信息
                match.group(4):球员耐力等信息
                match.group(5):球员动作计数信息
            '''
            dict_player['posx'] = match.group(2).split(' ')[2]
            dict_player['posy'] = match.group(2).split(' ')[3]
            dict_player['velx'] = match.group(2).split(' ')[4]
            dict_player['vely'] = match.group(2).split(' ')[5]
            dict_player['bodydir'] = match.group(2).split(' ')[6]
            dict_player['stamina'] = match.group(4).split(' ')[0]

            # 写入球员数据
            f_write.write(cycle + '|')
            f_write.write(str(i) + '|')
            f_write.write(dict_player['posx'] + '|')
            f_write.write(dict_player['posy'] + '|')
            f_write.write(dict_player['velx'] + '|')
            f_write.write(dict_player['vely'] + '|')
            f_write.write(dict_player['bodydir'] + '|')
            f_write.write(dict_player['stamina'] + '\n')

            i += 1

    f_write.close()

if __name__ == '__main__':
    # test
    rcg_to_db('/home/cqroot/RoboCup/AutoPlay/log/201903201709-HfutEngine_2-vs-MT2018_0.rcg', os.getcwd())
